package todo_app

type tMockTodoService struct {
	items  []*TodoDTO
	writer iTodoWriter
	reader iTodoReader
}

func newMockTodoService() ITodoService {
	it := new(tMockTodoService)
	it.init()
	return it
}

func (me *tMockTodoService) init() {
	me.writer = newTodoWriter()
	me.reader = newTodoReader()

	GlobalEventBus.Sub(EventReadTodoRet, "tMockTodoService", me.handleReadTodoRet)
}

func (me *tMockTodoService) handleReadTodoRet(e string, args interface{}) {
	switch e {
	case EventReadTodoRet:
		if it, ok := args.([]*TodoDTO); ok {
			me.items = it
		}
		break
	}
}

func (me *tMockTodoService) Create(it *TodoDTO) {
	GlobalEventBus.Pub(EventWriteTodoCmd, &TodoEvent{OPCreated, it.Clone()})
}

func (me *tMockTodoService) Update(it *TodoDTO) {
	GlobalEventBus.Pub(EventWriteTodoCmd, &TodoEvent{OPUpdated, it.Clone()})
}

func (me *tMockTodoService) Delete(it *TodoDTO) {
	GlobalEventBus.Pub(EventWriteTodoCmd, &TodoEvent{OPDeleted, it.Clone()})
}

func (me *tMockTodoService) GetAll() []*TodoDTO {
	me.items = nil
	GlobalEventBus.Pub(EventReadTodoCmd, nil)

	lst := me.items
	me.items = nil
	return lst
}

var MockTodoService = newMockTodoService()
